//
//  NetworkTool.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 27/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import Foundation
import AFNetworking

/// Shared network tool
let networkToolShared = NetworkTool.shared

class NetworkTool: AFHTTPSessionManager {
    
    static let shared: NetworkTool = {
        let tool = NetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    /// Make a request with given parameters, including a http request method
    ///
    /// - Parameters:
    ///   - url: a url string
    ///   - parameters: parameters
    ///   - method: http request method
    ///   - callBack: executes after received server response
    func request(url: String, parameters: [String: Any]? = nil, method: String, callBack:@escaping (_ responseObject: Any?)->()) {
        
        let success = { (task: URLSessionDataTask, response: Any?) in
            callBack(response)
        }
        let failure = { (task: URLSessionDataTask?, error: Error) in
            print(error)
            callBack(nil)
        }
        
        switch method {
        case "GET":
            get(url, parameters: parameters, progress: nil, success: success, failure: failure)
        case "POST":
            post(url, parameters: parameters, progress: nil, success: success, failure: failure)
        default:
            print("Request method error!")
            callBack(nil)
        }
        
    }
}



